package com.huawei.cloud.phone.management.adapter;

import com.huawei.cloud.phone.management.common.exception.BusinessException;
import com.huawei.cloud.phone.management.common.exception.InvalidParamException;
import com.huawei.cloud.phone.management.common.exception.SystemInnerException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
@Order(1)
public class GlobalExceptionHandler {

    /**
     * 处理业务异常
     *
     * @param exception 业务异常
     * @return 通用格式的异常
     */
    @ExceptionHandler(BusinessException.class)
    public ResponseEntity<?> handleException(BusinessException exception) {
        log.error("catch business exception", exception);
        return ResponseEntity.status(exception.getHttpCode()).body(exception);
    }

    /**
     * 处理非预期异常
     *
     * @param exception 非预期异常
     * @return 通用格式的异常
     */
    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<?> handleException(RuntimeException exception) {
        log.error("catch runtime exception", exception);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR.value()).body(new SystemInnerException());
    }

    /**
     * 处理参数校验异常，将参数校验异常转换为通用的异常格式
     *
     * @param exception 参数校验异常
     * @return 通用格式的异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<?> handleArgNotValidException(MethodArgumentNotValidException exception) {
        log.debug("catch exception", exception);
        InvalidParamException body = new InvalidParamException(exception.getBindingResult().getFieldErrors().get(0).getDefaultMessage());
        return ResponseEntity.status(HttpStatus.BAD_REQUEST.value()).body(body);
    }
}
